from fastapi import FastAPI, HTTPException, Request, status
from fastapi.responses import ORJSONResponse as JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.responses import PlainTextResponse, RedirectResponse
from starlette.templating import Jinja2Templates

from config.config import DOCS
from config.database import Base

from base.auth import Authentication
from base.middleware import AuthenticationMiddleware, CORSMiddleware

from app import admin


if DOCS:
    app = FastAPI(default_response_class=JSONResponse)
else:
    app = FastAPI(openapi_url=None, default_response_class=JSONResponse)


app.add_middleware(AuthenticationMiddleware, backend=Authentication())

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.mount("/admin", admin)


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(exc.detail, status_code=exc.status_code)


@app.exception_handler(Exception)
async def exception_handler(request, exc):
    headers = {"Access-Control-Allow-Origin": "*"}

    return PlainTextResponse("内部错误", status_code=500, headers=headers)


templates = Jinja2Templates(directory="static")


@app.get("/")
async def homepage(request: Request):
    """
    主页
    """

    return templates.TemplateResponse("index.html", {"request": request})


app.mount("/media", StaticFiles(directory="media"), name="media")
app.mount("/", StaticFiles(directory="static"), name="static")
